// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/exec/limit.h>

namespace kumo::pollux::exec {
    Limit::Limit(
        int32_t operatorId,
        DriverCtx *driverCtx,
        const std::shared_ptr<const core::LimitNode> &limitNode)
        : Operator(
              driverCtx,
              limitNode->outputType(),
              operatorId,
              limitNode->id(),
              "Limit"),
          remainingOffset_{limitNode->offset()},
          remainingLimit_{limitNode->count()} {
        isIdentityProjection_ = true;

        const auto numColumns = limitNode->outputType()->size();
        identityProjections_.reserve(numColumns);
        for (column_index_t i = 0; i < numColumns; ++i) {
            identityProjections_.emplace_back(i, i);
        }
    }

    bool Limit::needsInput() const {
        return !finished_ && input_ == nullptr;
    }

    void Limit::addInput(RowVectorPtr input) {
        POLLUX_CHECK_NULL(input_);
        input_ = input;
    }

    RowVectorPtr Limit::getOutput() {
        if (input_ == nullptr || (remainingOffset_ == 0 && remainingLimit_ == 0)) {
            return nullptr;
        }

        const auto inputSize = input_->size();

        if (remainingOffset_ >= inputSize) {
            remainingOffset_ -= inputSize;
            input_ = nullptr;
            return nullptr;
        }

        if (remainingOffset_ > 0) {
            // Return a subset of input_ rows.
            const auto outputSize =
                    std::min(inputSize - remainingOffset_, remainingLimit_);

            BufferPtr indices = allocate_indices(outputSize, pool());
            auto *rawIndices = indices->asMutable<vector_size_t>();
            std::iota(rawIndices, rawIndices + outputSize, remainingOffset_);

            auto output = fillOutput(outputSize, indices);
            remainingOffset_ = 0;
            remainingLimit_ -= outputSize;
            input_ = nullptr;
            if (remainingLimit_ == 0) {
                finished_ = true;
            }
            return output;
        }

        if (remainingLimit_ <= inputSize) {
            finished_ = true;
        }

        if (remainingLimit_ >= inputSize) {
            remainingLimit_ -= inputSize;
            auto output = input_;
            input_.reset();
            return output;
        }

        auto output = std::make_shared<RowVector>(
            input_->pool(),
            input_->type(),
            input_->nulls(),
            remainingLimit_,
            input_->children());
        input_.reset();
        remainingLimit_ = 0;
        return output;
    }
} // namespace kumo::pollux::exec
